package com.qqs.socket;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import com.qqs.util.ConvertUtil;

import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import io.netty.channel.ChannelHandlerContext;

public final class ChannelManager {
	private static Map<String, ChannelHandlerContext> channelMap = new HashMap();
	private static Map<String, ChannelHandlerContext> channelActiveMap = new HashMap();
	public static Map<String, ChannelHandlerContext> channelIpMap = new HashMap();

	public static Map<String, ChannelHandlerContext> getChannelMap() {
		return channelMap;
	}

	public static void setChannelMap(ChannelHandlerContext ctx) {
		String id = ctx.channel().toString().substring(5, 15);
		if (!channelMap.containsKey(id)) {
			channelMap.put(id, ctx);
		}
	}

	public static void SetChannelActiveMap(ChannelHandlerContext ctx) {
		String id = ctx.channel().toString().substring(5, 15);
		channelActiveMap.put(id, ctx);
	}

	public static void deleteChannel(ChannelHandlerContext ctx) {
		String id = ctx.channel().toString().substring(5, 15);
		channelActiveMap.remove(id, ctx);
		channelMap.remove(id);
		String ip = ConvertUtil.getIpFromSocketAddress(ctx.channel().remoteAddress());
		channelIpMap.remove(ip);
	}

	public static void checkChannelActive(long delay, long period) {
		Timer timer = new Timer();
		timer.scheduleAtFixedRate(new TimerTask() {
			public void run() {
				Map<String, ChannelHandlerContext> temp = new HashMap();
				temp.putAll(channelActiveMap);
				channelMap = temp;
				channelActiveMap = new HashMap();
				for (Entry<String, ChannelHandlerContext> entry : channelMap.entrySet()) {
					ChannelHandlerContext ctx = entry.getValue();
					channelIpMap.put(ConvertUtil.getIpFromSocketAddress(ctx.channel().remoteAddress()), ctx);
				}
			}
		}, delay, period);
	}
}
